const Cription = require('./static/Cription.js')
const Config = require('./config.js')
class Wifi extends Cription {
  constructor(cfg = Config) {
    super()
    this.cfg = {
      // 固件Wi-Fi配置信息
      wifiNamePassword: '12345678',
      address: '10.10.100.254',  // 固定值
      port: 9091,  // 固定值
      URL: 'https://oghafnxkic.execute-api.us-west-2.amazonaws.com/Prod/device/certificate/get',
      ...cfg,
    }
    this.udp = null
    this.msgLock = false
  }
  async connectWifi(ssid) {
    try {
      await wx.startWifi()
      await wx.connectWifi({
        SSID: ssid,
        password: this.cfg.wifiNamePassword
      })
      await wx.stopWifi()
      this.initUDP()
    } catch (e) {
      console.log('connect wifi error: ', e)
    }
  }
  initUDP() {
    const udp = wx.createUDPSocket()
    const port = udp.bind()  // 本地随机绑一个端口（空闲）
    console.log('udp bind port: ' + port)
    this.udp = udp
    udp.onMessage(msg => {
      if (!this.msgLock) {
        this.msgLock = true
        console.log('message: ', msg)
        const info = JSON.parse(this.decodeData(this.abToHex(msg.message)))
        console.log('message info: ', info)
        this.done && this.done(info)
      }
    })
    udp.onError(err => {
      console.log('error: ', err)
    })
    this.created && this.created()
  }
  sendData(jsonStr) {
    this.doing && this.doing()
    setTimeout(() => {
      this.udp.send({
        address: this.cfg.address,
        port: this.cfg.port,
        message: this.createData(jsonStr),
      })
    }, 1000)
  }
}
module.exports = Wifi